package dao

import (
	"fmt"
	"kandy/app/model"
	"kandy/framework"
	"log"
)

type UserDao struct {
}

func (this *UserDao) Insert(user *model.User) int64 {
	stmt, err := framework.DB.Prepare("INSERT INTO user(`username`,`password`,`create_time`) value(?,?,?)")
	if err != nil {
		log.Println(err.Error())
		return 0
	}
	defer stmt.Close()
	res, err := stmt.Exec(user.UserName, user.Password, user.CreateTime)
	if err != nil {
		log.Println("INSERT ERROR:", err)
		return 0
	}
	id, err := res.LastInsertId()
	if err != nil {
		return 0
	}
	return id

}

// GetUserByName 根据用户名来查询
func (this *UserDao) GetUserByName(username string) []model.User {
	stmt, err := framework.DB.Prepare("SELECT * FROM user WHERE `username` = ?")
	if err != nil {
		fmt.Println("查询错误:", err)
		return nil
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		fmt.Println("查询错误", err)
		return nil
	}
	var users []model.User

	for rows.Next() {
		user := model.User{}
		rows.Scan(&user.ID, &user.UserName, &user.Password, &user.CreateTime)
		users = append(users, user)
	}
	return users
}

// SelectAllUser 查找所有用户
func (this *UserDao) SelectAllUser() []model.User {
	stmt, err := framework.DB.Prepare("SELECT * FROM user")
	if err != nil {
		return nil
	}
	defer stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		return nil
	}

	users := make([]model.User, 0, 100)
	for rows.Next() {
		u := model.User{}
		rows.Scan(&u.ID, &u.UserName, &u.Password, &u.CreateTime)
		users = append(users, u)
	}
	return users
}
